import { useEffect } from 'react'
import Repo from '../components/Repo.jsx'
//import axios from 'axios'
const api = require('../lib/api')
import { Button, Icon, Tabs } from 'antd'
import getConfig from 'next/config'
import { connect } from 'react-redux'
import LRU from 'lru-cache'
import Router, { withRouter } from 'next/router'
import { cacheArray } from '../lib/repo-basic-cache'

const { publicRuntimeConfig } = getConfig()



const cache = new LRU({
  maxAge: 1000 * 60 * 10
})

const isServer = typeof window === 'nudefined'
function Index ({ userRepos, userStared, user, router }) {

  const tabKey = router.query.key || '1'

  const handleTabChange = (activeKey) => {
    Router.push(`/?key=${activeKey}`)
  }

  useEffect(() => {
    if (!isServer) {
      //cachedUserRepos = userRepos
      //cachedUserStaredRepos = userStared
      if (userRepos) {
        cache.set('userRepos', userRepos)
      }
      if (userStared) {
        cache.set('userStared', userStared)
      }
    }
  }, [userRepos, userStared])
  useEffect(() => {
    if (!isServer) cacheArray(userRepos)
  })

  if (!user || !user.id) {
    return (
      <div className="root">
        <p>亲！你还没有登录哦</p>
        <Button type="peimay" href={publicRuntimeConfig.OAUTH_URL}>点击登录</Button>

        <style jsx>{`
          .root{
            height:400px;
            display:flex;
            flex-direction:column;
            justify-content:center;
            align-items:center;
          }
          `}</style>
      </div>
    )
  }

  const {
    avatar_url, login, name, bio, email,
  } = user
  return (
    <div className="root">
      <div className="user-info">
        <img src={avatar_url} alt="" className="avatar" />
        <span className="login">{login}</span>
        <span className="name">{name}</span>
        <span className="bio">{bio}</span>
        <p className="email">
          <Icon type="mail" className="icon-email" />
          <a href={`mailto:${email}`}>{email}</a>
        </p>
      </div>

      <div className="user-repos">
        <Tabs defaultActiveKey={tabKey} onChange={handleTabChange} animated={false}>
          <Tabs.TabPane tab="你的仓库" key="1">
            {userRepos.map((repo) => (
              <Repo key={repo.id} repo={repo} />
            ))}
          </Tabs.TabPane>
          <Tabs.TabPane tab="你关注的仓库" key="2">
            {userStared.map((repo) => (
              <Repo key={repo.id} repo={repo} />
            ))}
          </Tabs.TabPane>
        </Tabs>
      </div>
      <style jsx>
        {`
          .root {
            display: flex;
            align-items: flex-start;
            padding: 20px 0;
          }

          .user-info {
            flex-shrink: 0;
            display: flex;
            flex-direction: column;
            width: 200px;
            margin-right: 40px;
          }

          .login {
            font-weight: 800;
            font-size: 20px;
            margin-top: 20px;
          }

          .name {
            font-size: 16px;
            color: #777;
          }

          .bio {
            margin-top: 20px;
            color: #333;
          }

          .avatar {
            width: 100%;
            border-radius: 5px;
          }

          .user-repos {
            flex: 1;
          }

          :global(.icon-email) {
            margin-right: 10px;
          }
        `}
      </style>
    </div >
  )
}


Index.getInitialProps = async ({ ctx, reduxStore, isLogoin }) => {
  const { user } = reduxStore.getState()
  let cachedUserRepos, cachedUserStaredRepos
  if (!user || !user.id) {
    return {
      isLogoin: false
    }
  }
  if (!isServer) {
    if (cache.get('userRepos') && cache.get('userStared')) {
      return {
        userRepos: cache.get('userRepos'),
        userStared: cache.get('userStared')
      }
    }
  }


  const userRepos = await api.request({ url: '/user/repos' }, ctx.req, ctx.res)
  const userStared = await api.request({ url: '/user/starred' }, ctx.req, ctx.res)
  if (!isServer) {
    cachedUserRepos = userRepos.data
    cachedUserStaredRepos = userStared.data
  }

  return {
    isLogoin: true,
    userRepos: userRepos.data,
    userStared: userStared.data

  }
}

export default connect(function mapState (state) {
  return {
    user: state.user
  }
},

)(withRouter(Index))
